﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;

namespace WinAPI.Management
{
    public class HWOperation
    {
        //disk["DriveType"] 的返回值意义如下:
        //1 No type
        //2 Floppy disk
        //3 Hard disk
        //4 Removable drive or network drive
        //5 CD-ROM
        //6 RAM disk

        public static void GetDisk()
        {
            SelectQuery query = new SelectQuery("Select * From Win32_LogicalDisk");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
            foreach (ManagementBaseObject disk in searcher.Get())
            {
                Console.WriteLine("\r\n" + disk["Name"] + " " + disk["DriveType"] + " " + disk["VolumeName"]);
            }
        }

        public static void GetDiskCapacity()
        {
            ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"c:\"");
            disk.Get();
            Console.WriteLine("Logical Disk Size = " + disk["Size"] + " bytes");
            Console.ReadLine();
        }

        public static void GetShareResource()
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_share");

            foreach (ManagementObject share in searcher.Get())
            {
                Console.WriteLine(share.GetText(TextFormat.Mof));
            }
        }


        //object[] obj = {"C:\\Temp","我的共享",0,10,"Dot Net 实现的共享",""};
        //改为
        //object[] obj = {"C:\\Temp","我的共享",0,null,"Dot Net 实现的共享",""};
        //就可以实现授权给最多用户了
        public static void CreateShareResource()
        {
            ManagementClass _class = new ManagementClass(new ManagementPath("Win32_Share"));
            object[] obj = { "C:\\Temp", "我的共享", 0, 10, "Dot Net 实现的共享", "" };
            _class.InvokeMethod("create", obj);
        }


        public static void GetServices()
        {
            ManagementObjectCollection queryCollection = null;
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Service");
            string[] lvData = new string[4];
            try
            {
                queryCollection = searcher.Get();
                foreach (ManagementObject mo in queryCollection)
                {
                    //create child node for operating system
                    lvData[0] = mo["Name"].ToString();
                    lvData[1] = mo["StartMode"].ToString();
                    if (mo["Started"].Equals(true))
                        lvData[2] = "Started";
                    else
                        lvData[2] = "Stop";
                    lvData[3] = mo["StartName"].ToString();
                }
            }
            catch (Exception e)
            {
            }
        }


        public static void SwitchToDHCP()
        {
            ManagementBaseObject inPar = null;
            ManagementBaseObject outPar = null;
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if (!(bool)mo["IPEnabled"])
                    continue;
                inPar = mo.GetMethodParameters("EnableDHCP");
                outPar = mo.InvokeMethod("EnableDHCP", inPar, null);
                break;
            }
        }

        public static void SwitchToStatic()
        {
            ManagementBaseObject inPar = null;
            ManagementBaseObject outPar = null;
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if (!(bool)mo["IPEnabled"])
                    continue;
                inPar = mo.GetMethodParameters("EnableStatic");
                inPar["IPAddress"] = new string[] { "192.168.0.102" };
                inPar["SubnetMask"] = new string[] { "255.255.255.0" };
                outPar = mo.InvokeMethod("EnableStatic", inPar, null);
                break;
            }
        }

        public static void ReportIP()
        {
            Console.WriteLine("****** Current IP addresses:");
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if (!(bool)mo["IPEnabled"])
                    continue;
                Console.WriteLine("{0}\n SVC: '{1}' MAC: [{2}]", mo["Caption"],
                                  mo["ServiceName"], mo["MACAddress"]);
                string[] addresses = (string[])mo["IPAddress"];
                string[] subnets = (string[])mo["IPSubnet"];
                Console.WriteLine(" Addresses :");
                foreach (string sad in addresses)
                    Console.WriteLine("\t'{0}'", sad);
                Console.WriteLine(" Subnets :");
                foreach (string sub in subnets)
                    Console.WriteLine("\t'{0}'", sub);
            }
        }


        private static void RomoteReboot(string[] args)
        {
            Console.WriteLine("Computer details retrieved using Windows Management Instrumentation (WMI)");
            Console.WriteLine("mailto:Written%2002/01/02%20By%20John%20O'Donnell%20-%20csharpconsulting@hotmail.com");
            Console.WriteLine("=========================================================================");
            //连接远程计算机
            ConnectionOptions co = new ConnectionOptions();
            co.Username = "john";
            co.Password = "john";
            ManagementScope ms = new ManagementScope("\\\\192.168.1.2\\root\\cimv2", co);
            //查询远程计算机
            ObjectQuery oq = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
            ManagementObjectSearcher query1 = new ManagementObjectSearcher(ms, oq);
            ManagementObjectCollection queryCollection1 = query1.Get();
            foreach (ManagementObject mo in queryCollection1)
            {
                string[] ss = { "" };
                mo.InvokeMethod("Reboot", ss);
                Console.WriteLine(mo.ToString());
            }
        }


        public static void CreateProcess()
        {
            //Get the object on which the method will be invoked
            ManagementClass processClass = new ManagementClass("Win32_Process");
            //Get an input parameters object for this method
            ManagementBaseObject inParams = processClass.GetMethodParameters("Create");
            //Fill in input parameter values
            inParams["CommandLine"] = "calc.exe";
            //Execute the method
            ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null);
            //Display results
            //Note: The return code of the method is provided in the "returnvalue" property of the outParams object
            Console.WriteLine("Creation of calculator process returned: " + outParams["returnvalue"]);
            Console.WriteLine("Process ID: " + outParams["processId"]);
        }


        public static int TerminateProcess(string[] args)
        {
            ManagementObject service =
                new ManagementObject("win32_service=\"winmgmt\"");
            InvokeMethodOptions options = new InvokeMethodOptions();
            options.Timeout = new TimeSpan(0, 0, 0, 5);
            ManagementBaseObject outParams = service.InvokeMethod("StopService", null, options);
            Console.WriteLine("Return Status = " + outParams["Returnvalue"]);
            return 0;
        }


        public static int GetRemoteInfo(string[] args)
        {
            ManagementObject disk = new ManagementObject(
                "win32_logicaldisk.deviceid=\"c:\"");
            disk.Get();
            Console.WriteLine("Logical Disk Size = " + disk["Size"] + " bytes");
            return 0;
        }

        //我使用WMI可以取出网卡的MAC地址，CPU的系列号，主板的系列号，其中主板的系列号已经核对过没有错的，其余的有待于验证，因为我使用的是笔记本，笔记本背面有一个主板的系列号，所以可以肯定主板系列号没有问题
        //网卡的MAC地址
        //SELECT MACAddress FROM Win32_NetworkAdapter WHERE ((MACAddress Is Not NULL) AND (Manufacturer <> 'Microsoft'))
        //结果：08:00:46:63:FF:8C

        //CPU的系列号
        //Select ProcessorId From Win32_Processor
        //结果：3FEBF9FF00000F24

        //主板的系列号
        //Select SerialNumber From Win32_BIOS
        //结果：28362630-3700521
        //获取硬盘ID
        public static void GetHDid()
        {
            String HDid;
            ManagementClass cimobject = new ManagementClass("Win32_DiskDrive");
            ManagementObjectCollection moc = cimobject.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                HDid = (string)mo.Properties["Model"].Value;
            }
        }

        public static void ExceptionHandle()
        {
            ManagementObjectCollection queryCollection;
            ConnectionOptions co = new ConnectionOptions();
            co.Username = "administrator";
            co.Password = "111";
            try
            {
                ManagementScope ms = new ManagementScope(@"\\csnt3\root\cimv2", co);
                ObjectQuery oq =
                    new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
                ManagementObjectSearcher query = new ManagementObjectSearcher(ms, oq);
                queryCollection = query.Get();
                foreach (ManagementObject mo in queryCollection)
                {
                    string[] ss = { "" };
                    mo.InvokeMethod("Reboot", ss);
                    Console.WriteLine(mo.ToString());
                }
            }
            catch (Exception ee)
            {
                Console.WriteLine("error");
            }
        }

        // Windows 管理规范 (WMI) 是可伸缩的系统管理结构，它采用一个统一的、基于标准的、可扩展的面向对象接口。WMI 为您提供与系统管理信息和基础 WMI API 交互的标准方法。WMI 主要由系统管理应用程序开发人员和管理员用来访问和操作系统管理信息。
        //WMI 可用于生成组织和管理系统信息的工具，使管理员或系统管理人员能够更密切地监视系统活动。例如，可以使用 WMI 开发一个应用程序，用于在 Web 服务器崩溃时呼叫管理员。
        //将 WMI 与 .NET 框架一起使用
        //WMI 提供了大量的规范以便为许多高端应用程序（例如，Microsoft Exchange、Microsoft SQL Server 和 Microsoft Internet 信息服务 (IIS)）实现几乎任何管理任务。管理员可以执行下列任务：
        //? 监视应用程序的运行状况。
        //? 检测瓶颈或故障。
        //? 管理和配置应用程序。
        //? 查询应用程序数据（使用对象关系的遍历和查询）。
        //? 执行无缝的本地或远程管理操作。
        //WMI 结构由以下三层组成：
        //? 客户端
        //使用 WMI 执行操作（例如，读取管理详细信息、配置系统和预订事件）的软件组件。
        //? 对象管理器
        //提供程序与客户端之间的中间装置，它提供一些关键服务，如标准事件发布和预订、事件筛选、查询引擎等。
        //? 提供程序
        //软件组件，它们捕获实时数据并将其返回到客户端应用程序，处理来自客户端的方法调用并将客户端链接到所管理的基础结构。
        //通过定义完善的架构向客户端和应用程序无缝地提供了数据和事件以及配置系统的能力。在 .NET 框架中，System.Management 命名空间提供了用于遍历 WMI 架构的公共类。
        //除了 .NET 框架，还需要在计算机上安装 WMI 才能使用该命名空间中的管理功能。如果使用的是 Windows Millennium Edition、Windows 2000 或 Windows XP，那么已经安装了 WMI。否则，将需要从 MSDN 下载 WMI。
        //用 System.Management 访问管理信息
        //System.Management 命名空间是 .NET 框架中的 WMI 命名空间。此命名空间包括下列支持 WMI 操作的第一级类对象：
        //? ManagementObject 或 ManagementClass：分别为单个管理对象或类。
        //? ManagementObjectSearcher：用于根据指定的查询或枚举检索 ManagementObject 或 ManagementClass 对象的集合。
        //? ManagementEventWatcher：用于预订来自 WMI 的事件通知。
        //? ManagementQuery：用作所有查询类的基础。
        //System.Management 类的使用编码范例对 .NET 框架环境很适合，并且 WMI 在任何适当的时候均使用标准基框架。例如，WMI 广泛利用 .NET 集合类并使用推荐的编码模式，如 .NET 异步操作的“委托”模式。因此，使用 .NET 框架的开发人员可以使用他们的当前技能访问有关计算机或应用程序的管理信息。
        //请参见
        //使用 WMI 管理应用程序 | 检索管理对象的集合 | 查询管理信息 | 预订和使用管理事件 | 执行管理对象的方法 | 远程处理和连接选项 | 使用强类型对象

        //获取CPU序列号代码
        public static void GetCpuInfo()
        {
            string cpuInfo = ""; //cpu序列号
            ManagementClass cimobject = new ManagementClass("Win32_Processor");
            ManagementObjectCollection moc = cimobject.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
                Console.WriteLine(cpuInfo);
                Console.ReadLine();
            }
        }

        public static void GetMacc()
        {
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if ((bool)mo["IPEnabled"])
                    Console.WriteLine("MAC address\t{0}", mo["MacAddress"]);
                mo.Dispose();
            }
        }


        private static void GetAccount(string[] args)
        {
            try
            {
                ManagementClass c = new ManagementClass("Win32_DiskQuota");
                ManagementObject quota = c.CreateInstance();
                quota["Limit"] = 400000000;
                quota["WarningLimit"] = 200000000;
                // Get user account object
                ManagementObject account = new ManagementObject("Win32_Account.Domain=TODAY20040216,Name=ASPNET");
                account.Get();
                // get disk object
                ManagementObject disk = new ManagementObject("Win32_LogicalDisk.DeviceId='F:'");
                disk.Get();
                quota["QuotaVolume"] = disk;
                quota["User"] = account;
                quota.Put(); // commit
                Console.WriteLine(c.SystemProperties);
                foreach (ManagementObject o in c.GetInstances())
                    Console.WriteLine("Next : {0}", o.Path);
            }
            catch (Exception e)
            {
                Console.WriteLine("error:" + e);
            }
        }
    }
}
